import {Button, Flex, Input, Modal, theme} from "antd";
import {Conversations, ConversationsProps} from "@ant-design/x";
import {DeleteOutlined, EditOutlined, PlusOutlined} from "@ant-design/icons";

import type {Conversation} from "@ant-design/x/es/conversations/interface";
import {useState} from "react";
import "./AiConversations.css";
import {useTheme} from "../../context/ThemeContext.tsx";
import * as chatController from "../../api/chatController";

interface ConversationProps {
    conversations: API.ConversationVO[];
    setConversations: (conversations: API.ConversationVO[]) => void;
    conversationId: string;
    setConversationId: (s: string) => void;
    onRemove: (s: string) => void;
    onTitleUpdate: (convId: string, title: string) => void;
}

export const AiConversations = (props: ConversationProps) => {
    const {
        conversations,
        setConversations,
        conversationId,
        setConversationId,
        onRemove,
        onTitleUpdate,
    } = props;

    const {token} = theme.useToken();
    const {theme: currentTheme} = useTheme();
    const isInk = currentTheme === 'ink';

    const [isModalOpen, setIsModalOpen] = useState(false);

    const [onUpdateConvId, setOnUpdateConvId] = useState("");
    const [updateTitle, setUpdateTitle] = useState("");

    const menuConfig: ConversationsProps["menu"] = (conversation) => ({
        items: [
            {
                label: "修改名称",
                key: "edit",
                icon: <EditOutlined/>,
                onClick: () => {
                    setIsModalOpen(true);
                    setOnUpdateConvId(conversation.key);
                },
            },
            {
                label: "删除会话",
                key: "del",
                icon: <DeleteOutlined/>,
                danger: true,
                onClick: () => {
                    chatController.del({conversationId: conversation.key}).then((response) => {
                        if (response.data && response.data.code === 0 && response.data.data) {
                            onRemove(conversation.key);
                        }
                    });
                },
            },
        ],
    });

    const onCreate = () => {
        // 生成新对话标题，格式为"对话X"，其中X是下一个可用数字
        const generateNewTitle = () => {
            // 查找当前所有对话标题中包含"对话X"格式的标题
            const conversationNumbers = conversations
                .map(conv => {
                    const match = (conv.title || "").match(/^对话(\d+)$/);
                    return match ? parseInt(match[1], 10) : 0;
                })
                .filter(num => num > 0);
            
            // 如果没有找到匹配的格式，从1开始
            if (conversationNumbers.length === 0) {
                return "对话1";
            }
            
            // 否则使用最大数字+1
            const maxNumber = Math.max(...conversationNumbers);
            return `对话${maxNumber + 1}`;
        };

        chatController.create().then((response) => {
            if (response.data && response.data.code === 0 && response.data.data) {
                const conv = response.data.data;
                if (conv) {
                    // 生成新的对话标题
                    const newTitle = generateNewTitle();
                    
                    // 创建新对话时立即更新标题
                    if (conv.conversationId) {
                        chatController.edit({
                            conversationId: conv.conversationId,
                            title: newTitle
                        }).then(() => {
                            // 添加新对话到列表并立即更新标题
                            setConversations([
                                ...conversations,
                                {
                                    conversationId: conv.conversationId,
                                    title: newTitle,
                                    messages: []
                                },
                            ]);
                            onConversationChange(conv.conversationId || "");
                        });
                    }
                }
            }
        });
    };

    const onConversationChange = (value: string) => {
        setConversationId(value);
    };

    const handleTitleUpdate = () => {
        chatController.edit({
            conversationId: onUpdateConvId,
            title: updateTitle
        }).then((response) => {
            if (response.data && response.data.code === 0 && response.data.data) {
                onTitleUpdate(onUpdateConvId, updateTitle);
                setIsModalOpen(false);
            }
        });
    };

    // 根据当前主题设置样式
    const inkStyle = {
        background: isInk ? `var(--gradient)` : `var(--gradient)`,
        color: '#f0f0f0',
        border: 'none',
        borderRadius: '24px',
        padding: '8px 20px',
        fontSize: '14px',
        fontFamily: 'var(--font-family)',
        boxShadow: 'var(--shadow)',
        position: 'relative' as const,
        overflow: 'hidden',
        transition: 'all 0.3s ease',
        width: 160,
        height: 40,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        margin: '20px 0',
    };

    const buttonClassName = isInk ? 'ink-button' : 'cartoon-button';

    return (
        <Flex
            style={{
                height: "100%",
                background: token.colorBgContainer,
                display: 'flex',
                flexDirection: 'column'
            }}
            vertical
        >
            <div style={{flex: 1, overflow: 'auto'}}>
                <Conversations
                    defaultActiveKey={conversationId}
                    activeKey={conversationId}
                    menu={menuConfig}
                    items={conversations.map((value) => {
                        return {
                            key: value.conversationId || "",
                            label: value.title || "新对话",
                            className: "card-hover transition-all"
                        } as Conversation;
                    })}
                    onActiveChange={onConversationChange}
                />
            </div>
            <Flex
                align={"center"}
                justify={"center"}
                style={{
                    padding: '16px',
                    borderTop: `1px solid var(--border-color)`,
                    background: isInk
                        ? 'linear-gradient(to bottom, transparent, rgba(0, 0, 0, 0.02))'
                        : 'linear-gradient(to bottom, transparent, rgba(255, 107, 107, 0.05))'
                }}
            >
                <Button
                    style={inkStyle}
                    icon={<PlusOutlined style={{fontSize: '16px'}}/>}
                    onClick={onCreate}
                    className={`${buttonClassName} animated-button`}
                >
                    新建会话
                </Button>
            </Flex>
            <Modal
                title={
                    <div style={{
                        fontFamily: 'var(--font-family)',
                        fontSize: '18px',
                        color: 'var(--text-color)',
                        borderBottom: `2px solid var(--primary-color)`,
                        paddingBottom: '8px'
                    }}>
                        修改会话名称
                    </div>
                }
                open={isModalOpen}
                onOk={handleTitleUpdate}
                onCancel={() => setIsModalOpen(false)}
                okButtonProps={{
                    style: {
                        background: `var(--gradient)`,
                        borderRadius: '20px',
                        fontFamily: 'var(--font-family)',
                    }
                }}
                cancelButtonProps={{
                    style: {
                        borderRadius: '20px',
                        fontFamily: 'var(--font-family)',
                    }
                }}
            >
                <Input
                    onChange={(e) => {
                        setUpdateTitle(e.target.value);
                    }}
                    style={{
                        borderRadius: '8px',
                        borderColor: token.colorBorderSecondary,
                        padding: '8px 12px',
                        fontFamily: 'var(--font-family)',
                    }}
                    placeholder="请输入新的会话名称"
                />
            </Modal>
        </Flex>
    );
};
